#pragma once 
#include<iostream>
#include<memory>
#include"Socket.hpp"
#include"Connection.hpp"

using namespace socket_ns;
class Listener
{
public:
    Listener(uint16_t port):_port(port),_listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BulidListenSocket(_port);
    }
    int ListenSocket()
    {
        return _listensock->Sockfd();
    }
    void Accepter(Connection* conn)
    {
        while(true)//ET模式下需要一次性将底层数据读完
        {
            errno=0;//错误码清0
            InetAddr addr;
            int code=0;
            int sockfd=_listensock->Accepter(&addr,&code);
            if(sockfd>0)
            {
                LOG(INFO,"accept success client ip:%s port:%d sockfd:%d\n",addr.Ip().c_str(),addr.Port(),sockfd);
                conn->_R->AddConnection(sockfd,EPOLLIN|EPOLLET,addr,NormalConnection);
            }
            else
            {
                if(code == EWOULDBLOCK)//下层链接已经读取完毕
                {
                    LOG(INFO,"底层链接获取完毕\n");
                    break;
                }
                else if(code == EINTR)//信号中断
                {
                    continue;
                }
                else
                {
                    LOG(ERROR,"获取链接出错\n");
                    break;
                }
            }
        }
    }
    ~Listener(){}
private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
};